package com.qf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qf.client.OrderClient;
import com.qf.dao.ShopRepository;
import com.qf.dao.UserRespository;
import com.qf.pojo.BaseResp;
import com.qf.pojo.ShopCart;
import com.qf.pojo.Toys;
import com.qf.pojo.User;
import com.qf.pojo.vo.Order;



import com.qf.service.ShopCartService;
import com.qf.utils.CookieUtils;

import com.qf.utils.JWTutils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class ShopCartServiceImpl implements ShopCartService {
    static String shopKey="SHOP_CART_";
//    @Autowired
//    ShopCartMapper shopCartMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ShopRepository shopRepository;
    @Autowired
    UserRespository userRespository;
    @Autowired
    OrderClient orderClient;
    @Override
    public BaseResp findAll(HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        //解析从request中获取到的token值
        CookieUtils cookieUtils = new CookieUtils();
        String token = cookieUtils.getToken(request);
        String o = (String)redisTemplate.opsForValue().get(token);
        //解析token,获取到其中的map值
//       String tokens = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzZWNyZXQiLCJ1aWQiOiI0IiwiaXNzIjoieHh5IiwidXNlck5hbWUiOiIxMjM0NTYiLCJpYXQiOjE2MTU3OTAwMzZ9.yhImrznDe-S6tIV3cCGdq1STdNb7OCEMb-5U9ObvJ4I";
        JWTutils jwTutils = new JWTutils();
        Map map = jwTutils.Verifier(o);
        //从map中获取到用户的id
        Object uid = map.get("id");
        //从redis中查询购物车信息
        List shop = redisTemplate.opsForHash().values(shopKey + uid.toString());
        if (shop!=null){
            baseResp.setMessage("查询成功");
            baseResp.setCode(200);
//            baseResp.setCount(count);
            baseResp.setData(shop);
            return baseResp;
        }
        return baseResp;
    }

    @Override
    public BaseResp addShopCart(Map map, HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        //解析从request中获得的token值
        CookieUtils cookieUtils = new CookieUtils();
        String token = cookieUtils.getToken(request);
        String o = (String)redisTemplate.opsForValue().get(token);
        //解析touken,获得其中的uid
        JWTutils jwTutils = new JWTutils();
//        String tokens = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzZWNyZXQiLCJ1aWQiOiI0IiwiaXNzIjoieHh5IiwidXNlck5hbWUiOiIxMjM0NTYiLCJpYXQiOjE2MTU3OTAwMzZ9.yhImrznDe-S6tIV3cCGdq1STdNb7OCEMb-5U9ObvJ4I";
        Map maps = jwTutils.Verifier(o);
        String uid = (String) maps.get("id");
        String shopId = map.get("sid").toString();
        //向redis中写入该用户的购物车内容
        Object obj = redisTemplate.opsForHash().get(shopKey + uid, shopId);
            //转换为json对象
            String string = JSONObject.toJSONString(obj);
            //转换为对象
            ShopCart shopCart = JSONObject.parseObject(string, ShopCart.class);
            shopCart.setNum(shopCart.getNum()+1);
            //将值存入redis中
            redisTemplate.opsForHash().put(shopKey + uid,shopId,shopCart);
            baseResp.setMessage("增加成功");
            baseResp.setCode(200);
        return baseResp;
    }

    @Override
    public BaseResp deletShopCart(Integer sid, HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        //从request中获取到token值
        CookieUtils cookieUtils = new CookieUtils();
        String token = cookieUtils.getToken(request);
        String o = (String)redisTemplate.opsForValue().get(token);
        //解析token,获取到用户id
        JWTutils jwTutils = new JWTutils();
//        String tokens = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzZWNyZXQiLCJ1aWQiOiI0IiwiaXNzIjoieHh5IiwidXNlck5hbWUiOiIxMjM0NTYiLCJpYXQiOjE2MTU3OTAwMzZ9.yhImrznDe-S6tIV3cCGdq1STdNb7OCEMb-5U9ObvJ4I";

        Map map = jwTutils.Verifier(o);
        String uid = (String) map.get("id");
        //首先判断该商品是否在购物车中
        Object obj = redisTemplate.opsForHash().get(shopKey + uid, sid.toString());
        if (obj!=null){
            //减少数量 当数量为1时，删除掉当前key，当数量大于1时，减少num数量
            //转换为对象
            String string = JSONObject.toJSONString(o);
            //将string转换为对象
            ShopCart shopCart = JSONObject.parseObject(string, ShopCart.class);
            //对shopCart中的num进行操作
            if (shopCart.getNum()>1){
                shopCart.setNum(shopCart.getNum()-1);
                redisTemplate.opsForHash().put(shopKey+uid,sid.toString(),shopCart);
            }else {
                redisTemplate.opsForHash().delete(shopKey+uid,sid.toString());
            }
        }
        baseResp.setCode(200);
        baseResp.setMessage("删除成功");
        return baseResp;
    }

    @Override
    public BaseResp add(Map map, HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        //解析从request中获得的token值
        CookieUtils cookieUtils = new CookieUtils();
        String token = cookieUtils.getToken(request);
        String o = (String)redisTemplate.opsForValue().get(token);
        //解析touken,获得其中的uid
//        String tokens = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzZWNyZXQiLCJ1aWQiOiI0IiwiaXNzIjoieHh5IiwidXNlck5hbWUiOiIxMjM0NTYiLCJpYXQiOjE2MTU3OTAwMzZ9.yhImrznDe-S6tIV3cCGdq1STdNb7OCEMb-5U9ObvJ4I";
        JWTutils jwTutils = new JWTutils();
        Map maps = jwTutils.Verifier(o);
        String uid = (String) maps.get("id");
        //向redis中写入该用户的购物车内容
        Integer sid = Integer.valueOf(map.get("sid").toString());
        Integer number = Integer.valueOf(map.get("number").toString());
        String shopId = sid.toString();
        //通过sid查询单个商品
        Optional<Toys> shop = shopRepository.findById(sid);

        Object obj = redisTemplate.opsForHash().get(shopKey + uid, shopId);
        if (obj!=null){
            //如果o不为空,则redis中有该商品,需要对该商品进行数量的增加
            Object o1 = redisTemplate.opsForHash().get(shopKey + uid, shopId);
            //转换为json对象
            String string = JSONObject.toJSONString(o1);
            //转换为对象
            ShopCart shopCart = JSONObject.parseObject(string, ShopCart.class);
            shopCart.setNum(shopCart.getNum()+number);
            //将值存入redis中
            redisTemplate.opsForHash().put(shopKey + uid,shopId,shopCart);
        }else {
            //当redis中没有商品时,将商品添加到redis中
            //转换为json对象
            String string = JSONObject.toJSONString(shop);
            //转换为toys对象
            Toys toys = JSONObject.parseObject(string, Toys.class);
            ShopCart shopCart = new ShopCart();
            BeanUtils.copyProperties(toys,shopCart);
            shopCart.setNum(number);
            redisTemplate.opsForHash().put(shopKey+uid,shopId,shopCart);
        }
        baseResp.setMessage("添加成功");
        baseResp.setCode(200);
        return baseResp;
    }

    @Override
    public BaseResp submit(Map map, HttpServletRequest request) {
        //解析从request中获得的token值
        CookieUtils cookieUtils = new CookieUtils();
        String token = cookieUtils.getToken(request);
        String o = (String)redisTemplate.opsForValue().get(token);
        //解析touken,获得其中的uid
//        String tokens = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzZWNyZXQiLCJ1aWQiOiI0IiwiaXNzIjoieHh5IiwidXNlck5hbWUiOiIxMjM0NTYiLCJpYXQiOjE2MTU3OTAwMzZ9.yhImrznDe-S6tIV3cCGdq1STdNb7OCEMb-5U9ObvJ4I";
        JWTutils jwTutils = new JWTutils();
        Map maps = jwTutils.Verifier(o);
        Integer uid = Integer.valueOf(maps.get("id").toString());
        //根据uid查询用户的信息
        Optional<User> user = userRespository.findById(uid);
        //将获取到的信息存入order中
        Order order = new Order();
        order.setCreateTime(new Date());
        order.setNum(Integer.valueOf(map.get("num").toString()));
        order.setPrice(Double.parseDouble(map.get("price").toString()));
        order.setUserName(user.get().getUserName());
        order.setStatus("未支付");
        return orderClient.submit(order);
    }

}
